package com.cloud.customtoastdemo.toast;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.cloud.customtoastdemo.R;

public class BaseEasyToast {
    private static final String TAG = "BaseEasyToast";
    private static View easyToastView;
    private static WindowManager mWindowManager;
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private static Runnable mToastRunnable;
    /**
     * 显示自定义Toast
     *
     * @param context  上下文
     * @param message  提示消息
     * @param duration 显示时长(毫秒)
     * @param gravity  显示位置(Gravity.TOP、Gravity.CENTER、Gravity.BOTTOM等)
     */
    public static void showCustomToast(Context context, String message, int duration, int gravity) {
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        easyToastView = inflater.inflate(R.layout.custom_easy_toast, null);
        TextView textView = easyToastView.findViewById(R.id.tv_message);
        textView.setText(message);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = gravity;
        params.x = 0;
        params.y = 0;

        if (easyToastView.getParent() == null) {
            mWindowManager.addView(easyToastView, params);
        }

        // 移除之前的任务
        if (mToastRunnable != null) {
            mHandler.removeCallbacks(mToastRunnable);
        }

        // 设置新的延时任务
        mToastRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "时间到了结束弹框" + duration);
                cancelEasyToast();
            }
        };
        mHandler.postDelayed(mToastRunnable, duration);
    }

    /**
     * 取消Toast显示
     */
    public static void cancelEasyToast() {
        if (easyToastView != null && easyToastView.getParent() != null) {
            mWindowManager.removeView(easyToastView);
        }
        if (mToastRunnable != null) {
            mHandler.removeCallbacks(mToastRunnable);
        }
    }
}